package com.gitee.free.coding.admin.system.logic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.free.coding.admin.system.entity.SystemUser;
import com.gitee.free.coding.admin.system.mapper.SystemUserMapper;
import com.gitee.free.coding.core.enums.SequenceEnum;
import com.gitee.free.coding.core.enums.TrueOrFalseEnum;
import com.gitee.free.coding.core.exceptions.FreeRuntimeException;
import com.gitee.free.coding.core.utils.ReturnVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SystemUserLogic {

    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 获取当前未注销用户的唯一标识
     *
     * @param userName 用户登录名
     * @return 当前未注销用户的唯一标识
     */
    public Integer getActiveUserId(String userName) {
        SystemUser activeUser = getActiveUserByUserName(userName);
        if (activeUser == null) {
            throw new FreeRuntimeException(-1, "当前用户不存在");
        }
        return activeUser.getId();
    }

    /**
     * 获取当前未注销用户信息
     *
     * @param userName 用户登录名
     * @return 当前未注销用户信息
     */
    public SystemUser getActiveUserByUserName(String userName) {
        QueryWrapper<SystemUser> systemUserQueryWrapper = new QueryWrapper<>();
        systemUserQueryWrapper.eq("user_name", userName);
        systemUserQueryWrapper.eq("deleted", TrueOrFalseEnum.FALSE.getBool());
        return systemUserMapper.selectOne(systemUserQueryWrapper);
    }

    /**
     * 新增用户
     *
     * @param userName 用户名、登录名
     * @return 用户表中的主键
     */
    public Integer addUser(String userName) {
        SystemUser systemUser = new SystemUser();
        Integer nextId = systemUserMapper.selectNextId();
        systemUser.setUserId(SequenceEnum.USER_ID.generateSerialNo(nextId));
        systemUser.setUserName(userName);
        // TODO 修改人获取方式  将用户信息存储到redis，然后从此处取出用户信息
        systemUser.setCreatedBy("");
        systemUser.setUpdatedBy("");
        int result = systemUserMapper.insert(systemUser);
        ReturnVerifier.verifyInsertOne(result, systemUser);
        // 获取回填的主键值
        return systemUser.getId();
    }
}
